package webengine

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"gin-api-server/core_library/global"
)

func CorsMiddleware() gin.HandlerFunc {

	corsConfig := global.Config.Cors

	return func(context *gin.Context) {
		method := context.Request.Method
		context.Header("Access-Control-Allow-Origin", corsConfig.AllowOrigin)
		context.Header("Access-Control-Allow-Headers", corsConfig.AllowHeaders)
		context.Header("Access-Control-Allow-Methods", corsConfig.AllowMethods)
		context.Header("Access-Control-Expose-Headers", corsConfig.ExposeHeaders)
		context.Header("Access-Control-Allow-Credentials", corsConfig.AllowCredentials)
		if method == "OPTIONS" {
			context.AbortWithStatus(http.StatusNoContent)
		}

		context.Next()
	}

}
